package org.ourgrid.peer.business.requester;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.ourgrid.common.interfaces.RemoteWorkerProvider;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.common.internal.response.RegisterInterestResponseTO;
import org.ourgrid.common.util.StringUtil;
import org.ourgrid.peer.PeerConstants;
import org.ourgrid.peer.business.dao.PeerDAOFactory;
import org.ourgrid.peer.dao.DiscoveryServiceClientDAO;
import org.ourgrid.peer.request.HereIsRemoteWorkerProvidersListRequestTO;

public class HereIsRemoteWorkerProvidersListRequester implements RequesterIF<HereIsRemoteWorkerProvidersListRequestTO> {

	public List<IResponseTO> execute(
			HereIsRemoteWorkerProvidersListRequestTO request) {
		
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		DiscoveryServiceClientDAO dao = PeerDAOFactory.getInstance().getDiscoveryServiceClientDAO();
		
		Set<String> oldProvidersServiceIds = new HashSet<String>();

		Collection<String> set = dao.getRemoteWorkerProvidersAddress();
		for ( String serviceId : set ) {
			oldProvidersServiceIds.add(serviceId);
		}
		
		for (int i = 0; i < request.getWorkerProvidersUserAtServer().size(); i++) {
			
			String peerAddress = request.getWorkerProvidersUserAtServer().get(i);
			String peerServiceId = request.getWorkerProvidersServicesIDs().get(i);
			
			if (peerAddress.equals(request.getMyUserAtServer())) {
				continue;
			}
			
			if (!oldProvidersServiceIds.remove( peerServiceId )){
				RegisterInterestResponseTO registerInterestResponse = new RegisterInterestResponseTO();
				registerInterestResponse.setMonitorableAddress(peerServiceId);
				registerInterestResponse.setMonitorableType(RemoteWorkerProvider.class);
				registerInterestResponse.setMonitorName(PeerConstants.DS_CLIENT);
				responses.add(registerInterestResponse);
				
				LoggerResponseTO loggerResponse = new LoggerResponseTO(
						"Receiving worker provider with id [" + peerAddress + "]", 
						LoggerResponseTO.DEBUG);
				responses.add(loggerResponse);
			}
		}
		
		for (String address : oldProvidersServiceIds) {
			NotifyRemoteWorkerProviderFailureRequester.markProviderAsDown(
					address, StringUtil.addressToUserAtServer(address), responses);
			
		}
		
		return responses;
	}

}
